package com.gzc.just.play.last.war.sceneserver.handler;

import com.gzc.just.play.last.war.common.handler.SimpleMessageHandler;
import com.gzc.just.play.last.war.sceneserver.battle.BattleManager;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 开始战斗处理器
 * 处理开始战斗的消息
 */
@Component
public class StartBattleHandler implements SimpleMessageHandler {
    private static final Logger logger = LoggerFactory.getLogger(StartBattleHandler.class);
    
    @Autowired
    private BattleManager battleManager;
    
    private static final int START_BATTLE = 1004;
    
    @Override
    public void handle(Object message, ChannelHandlerContext ctx) throws Exception {
        // 从上下文中获取玩家ID
        io.netty.util.AttributeKey<Long> playerIdKey = io.netty.util.AttributeKey.valueOf("playerId");
        Long playerId = ctx.channel().attr(playerIdKey).get();
        if (playerId == null) {
            logger.error("Player ID not found in context, cannot process start battle message");
            return;
        }
        
        // 获取玩家所在的战斗
        Long battleId = battleManager.getPlayerBattleId(playerId);
        if (battleId == null) {
            sendStartBattleResponse(ctx, false, "Not in any battle");
            return;
        }
        
        // 检查玩家是否是战斗创建者（示例：只有创建者可以开始战斗）
        // 在实际实现中，应该有更复杂的权限检查
        if (isBattleCreator(playerId, battleId)) {
            // 开始战斗
            if (battleManager.startBattle(battleId)) {
                // 发送开始成功响应
                sendStartBattleResponse(ctx, true, "Battle started successfully");
                
                logger.info("Player {} started battle: {}", playerId, battleId);
            } else {
                // 发送开始失败响应
                sendStartBattleResponse(ctx, false, "Failed to start battle");
                
                logger.warn("Player {} failed to start battle: {}", playerId, battleId);
            }
        } else {
            // 发送权限不足响应
            sendStartBattleResponse(ctx, false, "Only battle creator can start the battle");
            
            logger.warn("Player {} tried to start battle {} without permission", playerId, battleId);
        }
    }
    
    private boolean isBattleCreator(long playerId, long battleId) {
        // 实际实现中应该检查玩家是否是战斗创建者
        // 这里返回示例值
        return true;
    }
    
    private void sendStartBattleResponse(ChannelHandlerContext ctx, boolean success, String message) {
        // 实际实现中应该构造并发送开始战斗响应消息
        logger.info("Sending start battle response: success={}, message={}", success, message);
    }

    @Override
    public int getMessageId() {
        return START_BATTLE;
    }
    
    @Override
    public String getName() {
        return "StartBattleHandler";
    }
    
    @Override
    public Logger getLogger() {
        return logger;
    }
}